package main

import (
	"net"
	"strings"
)

type User struct {
	Name   string
	Addr   string
	C      chan string
	conn   net.Conn
	Server *Server
}

// 创建一个用户
func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()

	user := &User{
		Name:   userAddr,
		Addr:   userAddr,
		C:      make(chan string),
		conn:   conn,
		Server: server,
	}
	//开启携程，监听发给客户端的消息
	go user.ListenMessage()
	return user
}

// 用户监听chan上的数据
func (user *User) ListenMessage() {
	for {
		msg := <-user.C
		user.conn.Write([]byte(msg + "\n"))
	}
}

// 用户上线
func (user *User) Online() {
	//因为onlinemap是全局公用的，所以要加锁
	user.Server.mapLock.Lock()
	user.Server.OnlineMap[user.Name] = user
	user.Server.mapLock.Unlock()
	//用户上线消息发送到广播管道中
	user.Server.BroadCastUser(user, "online")
}

// 用户下线
func (user *User) offline() {
	//因为onlinemap是全局公用的，所以要加锁
	user.Server.mapLock.Lock()
	delete(user.Server.OnlineMap, user.Name)
	user.Server.mapLock.Unlock()
	//用户上线消息发送到广播管道中
	user.Server.BroadCastUser(user, "offline")
}

func (user *User) sendMsg(msg string) {
	user.C <- msg
}

// 用户发送消息到Server
func (user *User) doMessage(msg string) {
	if msg == "who" {
		//表示用户在查询在线用户列表
		user.Server.mapLock.Lock()
		for _, val := range user.Server.OnlineMap {
			message := "[" + val.Addr + "]" + val.Name + " online\n"
			user.sendMsg(message)
		}
		user.Server.mapLock.Unlock()

	} else if len(msg) > 7 && msg[:7] == "rename|" {
		newName := strings.Split(msg, "|")[1]
		notic := ""
		user.Server.mapLock.Lock()
		_, exist := user.Server.OnlineMap[newName]
		if exist {
			notic = string("the name alreay have")
		} else {
			delete(user.Server.OnlineMap, user.Name)
			user.Name = newName
			user.Server.OnlineMap[newName] = user
			notic = string("rename successfly：") + newName
		}
		user.Server.mapLock.Unlock()
		user.sendMsg(notic)
	} else if len(msg) > 4 && msg[:3] == "to|" {
		toName := strings.Split(msg, "|")[1]
		if toName == "" {
			user.sendMsg("私聊用户名称不能为空")
			return
		}
		toMessage := strings.Split(msg, "|")[2]
		if toMessage == "" {
			user.sendMsg("不能发送空消息")
		}
		toUser := user.Server.OnlineMap[toName]
		if toUser == nil {
			user.sendMsg("私聊用户不在线")
		}
		toUser.sendMsg(user.Name + " say to you：" + toMessage)
		return
	} else {
		user.Server.BroadCastUser(user, msg)
	}

}
